<template>
  <div>
    <!--header-->
    <van-nav-bar title="购物车" left-arrow :fixed="true" :z-index="9" :border="false" style="background-color: #f44;height: 50px;" @click-left="onClickLeft"/>
    <div v-if="itemList.length!==0">
      <!--购物车中商品-->
      <van-checkbox-group class="card-goods" v-model="checkedGoods" style="margin-top: 51px;margin-bottom: 56px;" @change="onClickSingleChecked">
        <van-checkbox class="card-goods__item" v-for="item in itemList" :key="item.id" :name="item.id" label-disabled>
          <van-card :title="item.itemName" :desc="item.description" :price="formatPrice(item.salePrice)" :thumb="item.itemPic.split('###')[0]" @click-thumb="toDetail(item)">
            <div slot="tags">
              规格：{{ item.itemGg }}
            </div>
            <div slot="num">
              <van-stepper v-model="item.buyNum" min="1" :max="item.itemNum" @change="onClickMinusPlus(item.id, item.buyNum)"/>
            </div>
          </van-card>
        </van-checkbox>
      </van-checkbox-group>
      <!--结算-->
      <van-submit-bar :price="totalPrice" :disabled="!checkedGoods.length" :button-text="submitBarText" @submit="onSubmit" style="height: 55px;">
        <van-checkbox v-model="selectAll" style="margin-left: 10px;" @change="onClickAllChecked">全选</van-checkbox>
        <van-button type="danger" size="mini" style="margin-left: 10px;" @click="onClickDelete">删除</van-button>
      </van-submit-bar>
    </div>
    <div v-else style="margin-top: 51px;">
      <div class="content">
        <div><img src="/img/cart_null.png"></div>
        <div><span style="font-size: 14px">你的购物车空空如也~</span></div>
        <div><van-button plain type="info" style="width: 30%;font-size: 14px" @click="onToGo">去逛逛</van-button></div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'cart',
  data () {
    return {
      checkedGoods: [], // 页面加载默认选中项，内容为 checked 的 name 属性值
      selectAll: false, // 全选按钮选中状态
      itemList: [] // 购物车商品列表
    }
  },
  computed: {
    /**
     * 结算商品数量计算
     */
    submitBarText () {
      const count = this.checkedGoods.length
      return '结算' + (count ? `(${count})` : '')
    },
    /**
     * 合计金额计算
     * 单位分，所以要乘100
     */
    totalPrice () {
      return this.itemList.reduce((total, item) => total + (this.checkedGoods.indexOf(item.id) !== -1 ? item.salePrice * item.buyNum * 100 : 0), 0)
    }
  },
  methods: {
    /**
     * 根据当前用户id查询其购物车列表
     */
    getItemListFromCartByOpenId (openId) {
      const self = this
      const param = { openId: openId }
      self.axios.get('api/shop/getItemListFromCartByOpenId', { params: param }).then(resp => {
        if (resp.data.code !== '-1') {
          resp.data.data.forEach(item => { // 如果购物数量超过库存，则将仅有库存赋值给购买数量
            if (item.buyNum > item.itemNum) {
              item.buyNum = item.itemNum
              this.onClickMinusPlus(item.id, item.buyNum)
            }
          })
          self.itemList = resp.data.data
        } else {
          self.$toast(resp.data.msg)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    /**
     * 去逛逛
     */
    onToGo () {
      this.$router.push({ name: 'category' })
    },
    /**
     * 返回上一页
     */
    onClickLeft () {
      this.$router.go(-1)
    },
    /**
     * 价格格式化
     */
    formatPrice (price) {
      return price.toFixed(2)
    },
    /**
     * 图片点击事件
     */
    toDetail (item) {
      this.$router.push({ name: 'detail', query: { itemId: item.itemId } })
    },
    /**
     * 数量增加、减少点击事件
     */
    onClickMinusPlus (id, buyNum) {
      const self = this
      const param = { id: id, buyNum: buyNum }
      self.axios.post('api/shop/updateItemNumOfCart', param).then(resp => {
        if (resp.data.code !== '-1') {
        } else {
          self.$toast(resp.data.msg)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    /**
     * 单选按钮事件
     */
    onClickSingleChecked () {
      const count = this.checkedGoods.length
      const allItemIdList = []
      const self = this
      self.itemList.forEach(item => {
        allItemIdList.push(item.id)
      })
      if (count !== 0 && count === allItemIdList.length) {
        self.selectAll = true
      } else {
        self.selectAll = false
      }
    },
    /**
     * 全选按钮事件
     */
    onClickAllChecked () {
      const count = this.checkedGoods.length
      const allItemIdList = []
      const self = this
      self.itemList.forEach(item => {
        allItemIdList.push(item.id)
      })
      if (count === 0 || count === allItemIdList.length) {
        if (self.selectAll) {
          // 由于可能全选之前，已有单选项目，所以要先清空
          self.checkedGoods = []
          self.itemList.forEach(item => {
            self.checkedGoods.push(item.id)
          })
        } else {
          self.checkedGoods = []
        }
      } else {
        if (self.selectAll) {
          // 由于可能全选之前，已有单选项目，所以要先清空
          self.checkedGoods = []
          self.itemList.forEach(item => {
            self.checkedGoods.push(item.id)
          })
        }
      }
    },
    /**
     * 商品删除
     */
    onClickDelete () {
      const self = this
      if (self.checkedGoods.length === 0) {
        self.$toast('请选择需要删除的商品')
      } else {
        this.$dialog.confirm({
          title: '提示',
          message: '选中的这些商品将会从您的购物车中移除'
        }).then(() => { // 确认
          const param = { ids: self.checkedGoods }
          self.axios.post('api/shop/deleteItemFromCart', param).then(resp => {
            if (resp.data.code !== '-1') {
              // 重新刷新购物车列表
              self.getItemListFromCartByOpenId(self.$store.state.openId)
              // 已选数量重置为空
              this.checkedGoods = []
              self.$toast('删除成功')
            } else {
              self.$toast(resp.data.msg)
            }
          }).catch(error => {
            console.log(error)
          })
        }).catch(() => { // 取消
          // on cancel
        })
      }
    },
    /**
     * 结算付款
     * payType 结算类型 1：购物车结算 2：直接结算
     */
    onSubmit () {
      this.$router.push({ name: 'orderConfirm', query: { ids: this.checkedGoods.join(','), payType: '1' } })
    }
  },
  mounted () {
    const self = this
    // 根据当前用户id查询其购物车列表
    self.getItemListFromCartByOpenId(self.$store.state.openId)
  }
}
</script>

<style lang="less">
.van-nav-bar .van-icon {
  color: white;
  vertical-align: middle;
}

.van-nav-bar__title {
  color: white;
}

.van-card__content {
  text-align: left;
  font-size: 14px;
}

.card-goods {
  padding: 10px 0;
  background-color: #fff;
  &__item {
    position: relative;
    background-color: #fafafa;
    .van-checkbox__label {
      width: 100%;
      height: auto; // temp
      padding: 0 10px 0 15px;
      box-sizing: border-box;
    }
    .van-checkbox__icon {
      top: 50%;
      left: 10px;
      z-index: 1;
      position: absolute;
      margin-top: -10px;
    }
    .van-card__price {
      color: #f44;
    }
  }
}

.content {
  margin: 150px auto 0;
  position: relative;
  top: 50%;
}
</style>
